import JSZip from 'jszip'
import mammoth from 'mammoth'
import { parseString } from 'xml2js'

// 解析样式元数据
export const parseStyles = async (file) => {
  const zip = await JSZip.loadAsync(file)
  const stylesXML = await zip.file('word/styles.xml').async('string')
  
  return new Promise((resolve, reject) => {
    parseString(stylesXML, (err, result) => {
      if (err) reject(err)
      
      const docDefaults = result['w:styles']['w:docDefaults'][0]
      const fonts = docDefaults['w:rPrDefault'][0]['w:rPr'][0]['w:rFonts'][0].$
      
      resolve({
        fonts: {
          main: fonts['w:ascii'] || 'Calibri',
          eastAsia: fonts['w:eastAsia'] || '宋体'
        }
      })
    })
  })
}

// 转换Word到HTML
export const convertDocxToHtml = async (file) => {
  const { value: html } = await mammoth.convertToHtml(
    { arrayBuffer: await file.arrayBuffer() },
    {
      styleMap: [
        "p[style-name='Heading 1'] => h1:fresh",
        "p[style-name='Heading 2'] => h2:fresh",
        "p[style-name='正文'] => p.font-main",
        "r[style-name='字体强调'] => span.font-emphasis",
        {
          selector: "r",
          convert: (element,{font}) => ({
            type: 'text',
            value: element.children[0].value,
            attributes: {
                "data-font": font?.name || "default",
              'data-font-size': element.size ? `${element.size}pt` : '12pt'
            }
          })
        }
      ],
      convertImage: mammoth.images.imgElement(async (image) => {
        const buffer = await image.read();
        const base64 = buffer.toString("base64");

        return {
          src: `data:${image.contentType};base64,${base64}`,
          style: `width: 100%; height: auto`,
        };
      }),
    }
  )
  return html
}